<template>
    <div>
        <el-form :model="form" label-width="100px" class="form-container">
        <el-row :gutter="20">
      <!-- 左侧栏 -->
      <el-col :span="8">
        <el-form-item label="单据编号：">
          <el-input 
            v-model="form.docNumber"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="单据阶段：">
          <el-select 
            v-model="form.stage"
            placeholder="请选择"
            clearable
          >
            <el-option
              label="已生效"
              value="active"
              :checked="form.stage === 'active'"
            />
            <!-- 其他选项可根据需要添加 -->
          </el-select>
        </el-form-item>
      </el-col>

      <!-- 中间栏 -->
      <el-col :span="10">
        <el-form-item label="单据日期：">
          <el-date-picker
            v-model="form.dateRange"
            type="daterange"
            range-separator="至"
            :start-placeholder="form.dateRange[0] || '请选择开始'"
            :end-placeholder="form.dateRange[1] || 'A'"
          />
        </el-form-item>

        <el-form-item label="已作废：">
          <el-select v-model="form.invalid" placeholder="否">
            <el-option label="否" value="no" />
            <el-option label="是" value="yes" />
          </el-select>
        </el-form-item>

       
      </el-col>

      <!-- 右侧操作按钮 -->
      <el-col :span="6" class="action-buttons">
        <el-button type="primary" @click="handleQuery">查</el-button>
        <el-button type="info" @click="handleReset">重</el-button>
        <el-button type="success" @click="toggleCollapse">收</el-button>
      </el-col>
    </el-row>
  </el-form>


    <div>
        <SalesOrderPage
            :table-data="tableData"
            :columns="tableColumns"
            :current-page="pageNo"
            :total="allPage"
            :page-size="pageSize"
            @page-change="handlePageChange"
            @action="handleTableAction"
            @edit="upDateSalesQuotes"
            @selection-change="handleSelectionChangeOrder"
            @row-audit="handleRowAudit"
            @delete="deleteDoc"
        ></SalesOrderPage> 
    </div>
<el-dialog
    v-model="auditDialogVisible"
    title="单据审核"
    width="600px"
    :close-on-click-modal="false"
>
    <el-form :model="auditForm" :rules="auditRules" ref="auditFormRef">
        <el-form-item label="单据编号：" prop="docCode">
            <el-input
                v-model="auditForm.docCode"
                disabled
                placeholder="系统自动填充"
            />
        </el-form-item>

        <el-form-item label="审核人：" prop="auditor">
            <el-select
                v-model="auditForm.auditor"
                placeholder="请选择审核人"
                filterable
                clearable
                style="width: 100%"
            >
                <el-option
                    v-for="user in auditors"
                    :key="user.id"
                    :label="`${user.name} (${user.dept})`"
                    :value="user.id"
                />
            </el-select>
        </el-form-item>

        <el-form-item label="审批意见：" prop="comment">
            <el-input
                v-model="auditForm.comment"
                type="textarea"
                :rows="3"
                placeholder="请输入审批意见"
                maxlength="200"
                show-word-limit
            />
        </el-form-item>
        <el-form-item label="审核结果：" prop="checkResult">
            <el-select
                v-model="auditForm.checkRes"
                placeholder="请选择审核结果"
                style="width: 100%"
            >
                <el-option label="通过" :value="true" />
                <el-option label="不通过" :value="false" />
            </el-select>
        </el-form-item>

    </el-form>

    <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">提交审核</el-button>
    </template>
</el-dialog>



    </div>
</template>


<script lang="ts" setup>
import { ref,reactive, toRaw } from 'vue';
import axios from 'axios';
import SalesReceivablePage from './SalesReceivablePage.vue';
import type { SalesReceivable } from '@/types/public-xs/salesDocuments';
import { useRoute,useRouter } from 'vue-router';
import {ElMessage,ElMessageBox} from 'element-plus';
import SalesOrderPage from '@/sales-order/SalesOrderPage.vue';
import request from '@/util/request';


let pageNo=ref(1)
let pageSize=ref(3)
let allPage=ref(0)
let route=useRoute()
let router=useRouter()
const form = reactive({
  docNumber: '',
  stage: 'active',
  dateRange: [],
  invalid: 'no',
  subject: ''
})

// 新增响应式数据
const auditDialogVisible = ref(false);
const auditFormRef = ref();
const auditForm = reactive({
    docCode: '',
    auditor: '',
    comment: '',
    checkRes: null
});

// 审核人列表（示例数据）
const auditors = ref([
    { id: 1, name: '张经理', dept: '财务部' },
    { id: 2, name: '李主管', dept: '销售部' }
]);

// 表单验证规则
const auditRules = reactive({
    auditor: [{ required: true, message: '请选择审核人', trigger: 'change' }],
    comment: [{ required: true, message: '请输入审批意见', trigger: 'blur' }],
    checkRes: [{ required: true, message: '请选择审核结果', trigger: 'change' }]
});

const handleQuery = () => {
    // 重置为第一页
    pageNo.value = 1
    // 传递表单查询参数
    fetchData(pageNo.value, {
        docCode: form.docNumber,
        stage: form.stage,
        invalid: form.invalid,
        startDate: form.dateRange[0] ? formatDate(form.dateRange[0]) : undefined,
        endDate: form.dateRange[1] ? formatDate(form.dateRange[1]) : undefined
    })
}

const handleReset = () => {
  Object.assign(form, {
    docNumber: '',
    stage: 'active',
    dateRange: [],
    invalid: 'no',
    subject: ''
  })
}

const toggleCollapse = () => {
  // 收起/展开逻辑
}

const tableColumns = ref([
  { prop: 'docCode', label: '单据编号' ,width:200},
  { prop: 'docDate', label: '单据日期' ,width:200},
  { prop: 'sourceSheet', label: '源单号' ,width:200},
  { prop: 'cidStr', label: '客户' },
  { prop: 'uidStr', label: '业务员', width:150},
  { prop: 'didStr', label: '部门' },
  { prop: 'status', label: '状态' },
  { prop: 'totalAmount', label: '应收总金额', width:200},
  { prop: 'receivedAmount', label: '已收余额'  },
  { prop: 'balanceAmount', label: '未收金额' },
  { prop: 'notes', label: '备注', width:150},
  { prop: 'dueDate', label: '到期日', width:150},
  { prop: 'settledAmount', label: '已核销金额', width:200},
  { prop: 'unsettledAmount', label: '未核销金额', width:200},
  { prop: 'typeColor', label: '红字单据' },
])

let tableData=ref<SalesReceivable[]>([])
    const handlePageChange = (newPage: number) => {
  pageNo.value = newPage;
  fetchData(newPage);
}
const formatDate = (date: Date, isEndDate: boolean = false) => {
    const pad = (num: number) => num.toString().padStart(2, '0');
    const year = date.getFullYear();
    const month = pad(date.getMonth() + 1);
    const day = pad(date.getDate());
    
    // 如果是结束日期，时间设为 23:59:59
    if (isEndDate) {
        return `${year}-${month}-${day} 23:59:59`;
    }
    return `${year}-${month}-${day} 00:00:00`;
};


const handleTableAction = (actionName: string) => {
      switch(actionName){
        case 'add':
          
          break
        case'check':
       
          break;
      }
    }

    async function fetchData(page: number, queryParams?: any) {
      const [startDate, endDate] = form.dateRange || []
     const params = {
            pageNo: page,
            pageSize: pageSize.value,
            docCode: form.docNumber,
            stage: form.stage,
            invalid: form.invalid,
            startDate: startDate ? formatDate(startDate) : undefined,
            endDate: endDate ? formatDate(endDate) : undefined
        }

    let response=await request.post('/cw/SalesReceivableController/selectSalesReceivableByPage',{
      ...params,
      ...queryParams
    })
    tableData.value=response.data.data.list
    console.log(tableData.value)
    allPage.value=response.data.data.total
   
}
fetchData(1)
const upDateSalesQuotes=(row: SalesReceivable)=>{
  router.push({
    name:'UpdateSalesOrder',
    params:{ 
      docCode: row.docCode // 传递单据编号
    }
  })
  
}

const selectedDocs = ref<string[]>([])


// 监听子组件选择事件
const handleSelectionChange = (selection: SalesReceivable[]) => {
    selectedDocs.value = selection.map(row => row.docCode)
}

const selectedOrder = ref<SalesReceivable[]>([])


// 监听子组件选择事件
const handleSelectionChangeOrder = (selection: SalesReceivable[]) => {
    selectedOrder.value = selection.map(row => row)
    console.log("拿对象", selectedOrder.value )
}

fetchData(1)

//审核方法
const handleRowAudit = (row: SalesReceivable) => {
    auditForm.docCode = row.docCode
    auditDialogVisible.value = true
    console.log('当前审核单据:', row.docCode)
}

//删除方法
const deleteDoc = async (row: SalesReceivable) => {
  try {
    // 1. 弹出确认框
    await ElMessageBox.confirm(
      '此操作将永久删除该销售报价单，是否继续？',
      '警告',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        // 可添加关闭前回调等其他配置
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true; // 确认按钮加载状态
            setTimeout(() => {
              done();
              instance.confirmButtonLoading = false;
            }, 300);
          } else {
            done();
          }
        }
      }
    );

    // 2. 用户确认后执行删除请求
    const response = await request.post('/cw/SalesReceivableController/deleteSalesReceivable', {
      docCode: row.docCode
    });

    // 3. 处理响应结果
    if (response.data.code == 200) {
      ElMessage.success('删除成功');
      fetchData(1);
    } else {
      ElMessage.error('删除失败');
    }
  } catch (error) {
    // 4. 用户点击取消或关闭弹窗时触发 catch
    if (error === 'cancel') {
      ElMessage.info('已取消删除');
    } else {
      ElMessage.error('请求异常：' + error);
    }
  }
};


const submitAudit = async () => {
    // 表单验证
    if (!await auditFormRef.value?.validate()) return;



    try {
        const response = await request.post('/cw/xs/check', {
            docCode: auditForm.docCode,
            typeId: 2,
            status: 3,
            checkManId: auditForm.auditor,  // 绑定审核人ID
            checkComment: auditForm.comment, // 绑定审批意见
            checkRes: auditForm.checkRes // 绑定审核结果
        });

        ElMessage.success(response.data.message);
        auditDialogVisible.value = false;
        fetchData(pageNo.value); // 刷新表格数据
    } catch (error) {
        ElMessage.error('审核提交失败');
    } finally {
        // 重置表单
        auditForm.auditor = '';
        auditForm.comment = '';
    }
};

</script>

<style scoped>


</style>